import { computed } from 'vue'
import type { DiyStore } from '@/entity/DiyStore'
import { TextStyle } from '@/diy/config/DiyText'
import { getPxValue, setPxValue } from '@/utils'

export const useDiyHooks = <T extends DiyStore>(store: T) => {
  //因为样式都是字符串类型，但是操作时是数字类型的，需要改函数辅助
  const generateStyleProp = (key: keyof TextStyle) => {
    return computed({
      get() {
        return getPxValue(store.currentComponent?.style[key])
      },
      set(value: number) {
        ;(store.currentComponent?.style as any)[key] = setPxValue(value)
      }
    })
  }

  //画布是否可以拖动
  const draggable = computed(() => !store.currentComponent)

  //获取标尺的辅助线坐标
  const handleGetGuidelines = (data: any) => {
    Object.assign(store.guidelines, data)
  }

  //更改画布信息
  const handleSetCanvasStyle = (style: Record<string, any>) => {
    const { left, top, width, height } = style

    if (left || top) {
      //设置画布位置信息
      store.previewData.globalSetting.canvasX = left || 0
      store.previewData.globalSetting.canvasY = top || 0
    }

    //设置画布大小信息
    if (width && height) {
      store.previewData.globalSetting.canvasWidth = width
      store.previewData.globalSetting.canvasHeight = height
    }
  }

  return {
    draggable,
    handleGetGuidelines,
    handleSetCanvasStyle,
    generateStyleProp
  }
}
